package com.woniuxy.activiti.controller;

import com.woniuxy.activiti.service.ActFlowCommService;
import com.woniuxy.activiti.service.EnterpriseCreditService;
import com.woniuxy.entity.BusinessInfo;
import com.woniuxy.entity.EnterpriseCredit;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import com.woniuxy.service.business.BorrowDemandService;
import com.woniuxy.utils.JWTUtil;
import com.woniuxy.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author xilei
 * @create 2021-11-15 12:45
 */
@Slf4j
@RestController
public class EnterpriseCreditController {

    @Autowired
    private EnterpriseCreditService enterpriseCreditService;
    @Autowired
    private ActFlowCommService actFlowCommService;
    @Autowired
    private UserService userService;

    @Autowired
    private BorrowDemandService borrowDemandService;

    /**
     * 查询业务员用户id所有授信
     * @param
     * @return
     */
    @GetMapping("/enterprisecredit/findall")
    public List<EnterpriseCredit> findAll(HttpServletRequest request) {
        String authentication = request.getHeader("authentication");
        String uname = JWTUtil.getUname(authentication);
        User user = userService.getUser(uname);
        int userId = user.getId();
        log.info("获取到的登录用户ID未:{}", userId);
        log.info("获取到的登录用户名未:{}", uname);
        List<EnterpriseCredit> creditList = enterpriseCreditService.findCreditsByUserId(userId);
        return creditList;
    }
    @GetMapping("/enterprisecredit/userId/{userId}")
    public List<EnterpriseCredit> findCreditByUserId(@PathVariable("userId") int userId){

        return enterpriseCreditService.findCreditsByUserId(userId);
    }

    @GetMapping("/enterprisecredit/id/{id}")
    public EnterpriseCredit findCreditById(@PathVariable("id") int id){

        EnterpriseCredit credit = enterpriseCreditService.findCreditById(id);
        System.out.println("credit------++++++:"+credit);
        Integer ceid = credit.getCoreEnterprise().getId();
        int mid = credit.getMerchandiser().getId();
        ResponseResult<BusinessInfo> businessrr = borrowDemandService.getBusinessInfoById(ceid);
        credit.setCoreEnterprise(businessrr.getData());
        User user = userService.getUser(mid);
        credit.setMerchandiser(user);
        return credit;

    }

    @GetMapping("/enterprisecredit/enterpriseId/{enterpriseId}")
    public List<EnterpriseCredit> findCreditByEnterpriseId(@PathVariable("enterpriseId") int enterpriseId){

        return enterpriseCreditService.findCreditByEnterpriseId(enterpriseId);
    }

    /**
     * 新增授信申请
     *
     * @param enterpriseCredit
     */
    @PostMapping("/enterprisecredit/add")
    public void addEnterpriseCredit(HttpServletRequest request, @RequestBody EnterpriseCredit enterpriseCredit){
        String authentication = request.getHeader("authentication");
        String uname = JWTUtil.getUname(authentication);
        User user = userService.getUser(uname);
        int userid = user.getId();
        System.out.println("000"+enterpriseCredit);
        enterpriseCredit.getMerchandiser().setId(userid);
        log.info("==获取到的登录用户名未:{}",uname);
        enterpriseCredit.setState(0);
        enterpriseCredit.setTaskStartTime(new Date());
        enterpriseCredit.setLoanProductName("供应链企业授信贷款");

        int code = enterpriseCreditService.addEnterpriseCredit(enterpriseCredit);
        if (code == 1){
            System.out.println("enterpriseCredit"+enterpriseCredit);
            System.out.println(enterpriseCredit.getId());
            int id = enterpriseCredit.getId();

            String formKey = "enterpriseCredit";
            String beanName = formKey+"Service";
            //使用流程变量设置字符串（格式 ： Evection:Id 的形式）
            String bussinessKey = formKey+":"+id;
            System.out.println("formKey---------------"+formKey);
            System.out.println("beanName---------------"+beanName);
            System.out.println("bussinessKey---------------"+bussinessKey);
            System.out.println("id---------------"+id);
            ProcessInstance processInstance = actFlowCommService
                    .startProcess(formKey, beanName, bussinessKey, id);
//            流程实例ID
            String processDefinitionId = processInstance.getProcessDefinitionId();
            log.info("processDefinitionId:{}",processDefinitionId);
            System.out.println("processDefinitionId-------"+processDefinitionId);
            List<Map<String, Object>> taskList =
                    actFlowCommService.myTaskList(String.valueOf(userid));
            if (!CollectionUtils.isEmpty(taskList)){
                for (Map<String,Object> map:taskList){
                    System.out.println("assignee:"+map.get("assignee"));
                    System.out.println("userid:"+userid);
                    System.out.println("processDefinitionId1:"+map.get("processDefinitionId"));
                    System.out.println("processDefinitionId2:"+processDefinitionId);
                    System.out.println(map.get("assignee").toString().equals(userid));
                    System.out.println(map.get("processDefinitionId").toString().equals(processDefinitionId));
                    if (map.get("assignee").toString().equals(String.valueOf(userid))&&
                    map.get("processDefinitionId").toString().equals(processDefinitionId)){
                        System.out.println("进去map方法中");
                        log.info("processDefinitionId is {}"
                                ,map.get("processDefinitionId").toString());
                        log.info("taskid is {}",map.get("taskid").toString());
                        actFlowCommService.completeProcess("同意", map.get("taskid").toString(), String.valueOf(userid));
                    }
                }
            }
        }
    }
}
